const express = require('express');
const router = express.Router();

const { multer } = require('../../model/tools');
const fs = require('fs');

const ArticleCateModel = require('../../model/articleCateModel');
const ArticleModel = require('../../model/articleModel');


router.get('/', async (req, res)=>{

  let page = req.query.page || 1;
  let pageSize = 5;

  let list = await ArticleModel.aggregate([
    {
      $lookup: {
        from: 'article_cate',
        localField: 'cid',
        foreignField: '_id',
        as: 'cate'
      }
    },
    {
      $sort: {
        add_time: -1
      }
    },
    {
      $skip: (page-1)*pageSize
    },
    {
      $limit: pageSize
    }
  ])

  // let list = await ArticleModel.find({}).skip((page-1)*pageSize).limit(pageSize);
  let count = await ArticleModel.count();
  res.render('admin/article/index.html',{ 
    list,
    totalPages: Math.ceil(count/pageSize),
    page
  })
});

router.get('/add', async (req, res)=>{
  let result = await ArticleCateModel.aggregate([
    {
      $lookup: {
        from: 'article_cate',
        localField: '_id',
        foreignField: 'pid',
        as: 'items'
      }
    },
    {
      $match: {
        pid: '0'
      }
    }
  ]);
  res.render('admin/article/add.html', {
    articleCate: result
  })
});

router.post('/doAdd', multer().single('article_img'), async (req, res)=>{
  try {
    let imgSrc = req.file? req.file.path.substr(7): '';
    let result = new ArticleModel(Object.assign(req.body, {'article_img': imgSrc}));
    await result.save();
    res.redirect(`/${req.app.locals.adminPath}/article`);
  } catch (error) {
    res.render('admin/public/error.html', {
      message: '增加文章内容失败',
      redirectUrl: `/${req.app.locals.adminPath}/article/add`
    });
  }
});

router.get('/edit', async (req, res)=>{
  let id = req.query.id;
  let articleResult = await ArticleModel.find({_id: id});

  let cateResult = await ArticleCateModel.aggregate([
    {
      $lookup: {
        from: 'article_cate',
        localField: '_id',
        foreignField: 'pid',
        as: 'items'
      }
    },
    {
      $match: {
        pid: '0'
      }
    }
  ]);
  res.render('admin/article/edit', {
    list: articleResult[0],
    articleCate: cateResult
  })
});

router.post('/doEdit', multer().single('article_img'), async (req, res)=>{
  try {
    if(req.file){ //更新图片
      // 1.更改图片路径
      let article_img = req.file?req.file.path.substring(7):'';
      let originImg = req.body.origin_img;
      await ArticleModel.updateOne({_id: req.body.id}, Object.assign(req.body, {article_img: article_img}))
      // 2.删除原来的图片
      if(originImg){
        await fs.unlink('static/'+originImg, err=>{
          if(err){
            console.log(err);
          }
        })
      }
    }else{
      await ArticleModel.updateOne({_id: req.body.id}, req.body)
    }
    res.render('admin/public/success.html', {
      message: '修改文章内容成功',
      redirectUrl: `/${req.app.locals.adminPath}/article`
    });
  } catch (error) {
    res.render('admin/public/error.html', {
      message: '修改文章内容失败',
      redirectUrl: `/${req.app.locals.adminPath}/article/edit?id=${req.body.id}`
    });
  }
});

router.get('/delete', async (req, res)=>{
  let id = req.query.id;
  let resultList = await ArticleModel.find({_id: id});
  let delResult = await ArticleModel.deleteOne({_id: req.query.id});
  //删除图片
  if(delResult.ok == 1 && delResult.n == 1){
    if(resultList[0].article_img){
      await fs.unlink('static/'+resultList[0].article_img, err=>{
        if(err){
          console.log(err);
        }
      })
    }
  }
  res.render('admin/public/success.html', {
    message: '删除文章成功',
    redirectUrl: `/${req.app.locals.adminPath}/article`
  });
});

router.post('/doUploadImage', multer().single('file'), (req, res)=>{
  // 获取文件路径，去除 static/
  let imgSrc = req.file?req.file.path.substring(7):'';
  // 返回一个json数据
  res.send({
    link: '/'+imgSrc
  })
});

router.post('/doUploadVideo', multer().single('file'), (req, res)=>{
  // 获取文件路径，去除 static/
  let videoSrc = req.file?req.file.path.substring(7):'';
  // 返回一个json数据
  res.send({
    link: '/'+videoSrc
  })
});

module.exports = router;